<script setup>
  import { computed, getCurrentInstance, onMounted, ref } from 'vue'
  const freeList = defineProps({
    list: Array,
  })

  // 选中的值
  const activeIndex = ref(0)

  // 每个tab栏项目的节点值
  // const tabList = ref([])

  // tab栏项目中下方文字的宽度
  const fsTabList = ref([])

  // 下滑块的宽度
  const cursorWidth = ref(0)

  const ctabLeft = ref(0)

  // 获取每个tab栏节点的left值和width值
  onMounted(() => {
    // 1.创建节点查询器
    let querySelect = uni.createSelectorQuery().in(getCurrentInstance())

    // 获取最大盒子块节点信息
    // querySelect.selectAll('.custom-tabs-bar').boundingClientRect((res) => {
    //   tabList.value = res.map(({ width, left }) => ({ width, left }))
    // })

    // 2.获取文字节点信息
    querySelect.selectAll('.tabbar-text').boundingClientRect((res) => {
      fsTabList.value = res.map(({ width, left }) => {
        return {
          width,
          left,
        }
      })
    })
    // 3.获取滑动块节点信息
    querySelect.select('.custom-tabs-cursor').boundingClientRect((res) => {
      cursorWidth.value = res.width
    })

    // 获取被相对定位值的left值
    querySelect.select('.custom-tabs').boundingClientRect((res) => {
      ctabLeft.value = res.left
    })

    // 4.执行查询
    querySelect.exec()
  })

  // 计算tab栏下方盒子的left值
  const cursorleft = computed(() => {
    // if (tabList.value.length === 0) return
    if (cursorWidth.value === 0) return
    // 大盒子的宽度
    // const { left, width } = tabList.value[activeIndex.value]
    // 文字的宽度
    const { width: fsWidth, left: fsLeft } = fsTabList.value[activeIndex.value]

    return (fsWidth - cursorWidth.value) / 2 + fsLeft - ctabLeft.value
  })

  const emit = defineEmits(['click'])

  // 点击导航栏的选项后
  // 传递给父组件数据
  function slectTabFn(index, item) {
    activeIndex.value = index
    // console.log(activeIndex.value)
    emit('click', item, index)
  }
</script>

<template>
  <view class="custom-tabs">
    <view
      class="custom-tabs-bar"
      v-for="(item, index) in freeList.list"
      v-bind:key="index"
      v-bind:class="{ active: index === activeIndex }"
      @click="slectTabFn(index, item)"
    >
      <text class="tabbar-text">{{ item.label }}</text>
    </view>

    <view
      class="custom-tabs-cursor"
      :style="{ left: cursorleft + 'px' }"
    ></view>
  </view>
</template>

<style lang="scss">
  // 自定义tabbar
  .custom-tabs {
    display: flex;
    position: relative;
    justify-content: flex-start;
    padding: 0 30rpx;
  }

  .custom-tabs-bar {
    height: 80rpx;
    padding-right: 10rpx;
    line-height: 80rpx;
    color: #979797;
    position: relative;

    &.active {
      color: #121826;
      font-weight: 500;
    }
  }

  .tabbar-text {
    font-size: 30rpx;
  }

  .custom-tabs-cursor {
    position: absolute;
    bottom: 3px;
    left: 20px;

    width: 20px;
    height: 2px;
    border-radius: 2px;
    background-color: #2cb5a5;
    transition: all 0.3s ease-out;
  }
</style>
